package com.earthea.scaffold.service.impl;

import com.earthea.scaffold.entity.domain.Message;
import com.earthea.scaffold.mapper.MessageMapper;
import com.earthea.scaffold.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;

    @Override
    public List<Message> selectAll() {
        List<Message> all = messageMapper.selectAll();
        Map<Long, Message> map = all.stream().collect(Collectors.toMap(Message::getId, Function.identity()));
        List<Message> roots = new ArrayList<>();
        for (Message message : all) {
            if (message.getParentId() == -1L) {
                roots.add(message);
            } else {
                Message parent = map.get(message.getParentId());
                if (parent != null) {
                    parent.getChildren().add(message);
                }
            }
        }
        return roots;
    }

    @Override
    public int insert(Message message) {
        return messageMapper.insert(message);
    }
}
